<script setup lang='ts'>
import { User, Lock, Key, Message } from '@element-plus/icons-vue';
import { reactive } from 'vue';
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElNotification } from 'element-plus';
import { getTime } from '../../utils/time'
import useUserStore from '../../store/modules/user'
import { reqCaptcha } from '../../apis/user';
import { onMounted } from 'vue';
import type { ElInput } from 'element-plus'



const usernameInput = ref<InstanceType<typeof ElInput>>()
const emailInput = ref<InstanceType<typeof ElInput>>()
const passwordInput = ref<InstanceType<typeof ElInput>>()
const captchaInput = ref<InstanceType<typeof ElInput>>()
let captchaSrc = ref<string>('')
const $router = useRouter()
const time = getTime()
const useUser = useUserStore()
const loginType = ref<boolean>(true)
const loginRef = ref()
const loading = ref<boolean>(false)
const loginDate = ref({
  username: '',
  email: '',
  password: '',
  captcha: ''
})

onMounted(() => {
  getCaptcha()
})

// 表单校验规则
const formRules = reactive({
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur'
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    }
  ],
  email: [
    {
      required: true,
      message: '请输入邮箱',
      trigger: 'blur'
    }
  ],
  captcha: [
    {
      required: true,
      message: '请输入验证码',
      trigger: 'blur'
    }
  ]
})

const changeLoginType = () => {
  loginType.value = !loginType.value
  handlerClean()
}

const handlerLogin = async () => {
  await loginRef.value.validate()
  loading.value = true
  try {
    const msg = await useUser.userLogin(loginDate.value)
    if (msg === 'ok') {
      $router.push('/')
      ElNotification.success({
        title: `欢迎回来! ${useUser.userName}`,
        message: `${time}好!`,
      })
      loading.value = false
    }

  } finally {
    handlerClean()
    getCaptcha()
  }
}


const getCaptcha = async () => {
  const res = await reqCaptcha()
  captchaSrc.value = res
}

const goRegister = () => {
  handlerClean()
  $router.push('/register')
}

const handlerClean = () => {
  Object.assign(loginDate.value, {
    username: '',
    email: '',
    password: '',
    captcha: ''
  })
}


const handleEnter = (field: string) => {
  const fieldsOrder = loginType.value
    ? [usernameInput, passwordInput, captchaInput]
    : [emailInput, passwordInput, captchaInput]

  const currentIndex = fieldsOrder.findIndex(ref => ref === {
    username: usernameInput,
    email: emailInput,
    password: passwordInput,
    captcha: captchaInput
  }[field])

  if (currentIndex < fieldsOrder.length - 1) {
    fieldsOrder[currentIndex + 1]?.value?.focus()
  } else {
    handlerLogin()
  }
}
</script>


<template>
  <div class="login_container">
    <!-- 添加30个流星元素 -->
    <div v-for="n in 30" :key="n" class="meteor"></div>

    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-form class="login_form" :rules="formRules" ref="loginRef" :model="loginDate">
          <h1>Hello</h1>
          <h2>欢迎来到TAPD</h2>
          <div class="form">
            <el-form-item prop="username" v-if="loginType">
              <el-input :prefix-icon="User" v-model="loginDate.username" placeholder="请输入用户名"
                @keydown.enter="handleEnter('username')" ref="usernameInput" clearable />
            </el-form-item>
            <el-form-item prop="email" v-else>
              <el-input :prefix-icon="Message" v-model="loginDate.email" placeholder="请输入邮箱"
                @keydown.enter="handleEnter('email')" ref="emailInput" clearable />
            </el-form-item>
            <el-form-item prop="password">
              <el-input :prefix-icon="Lock" v-model="loginDate.password" placeholder="请输入密码"
                @keydown.enter="handleEnter('password')" ref="passwordInput" type="password" show-password clearable />
            </el-form-item>
            <el-form-item prop="captcha">
              <el-input :prefix-icon="Key" v-model="loginDate.captcha" placeholder="请输入验证码"
                @keydown.enter="handleEnter('captcha')" ref="captchaInput">
                <template #append>
                  <img :src="captchaSrc" alt="" style="width: 100px;height: 32px;" @click="getCaptcha">
                </template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-link type="primary" @click="changeLoginType" v-if="loginType">切换邮箱登录</el-link>
              <el-link type="primary" @click="changeLoginType" v-else>切换用户名登录</el-link>
              <el-button type="primary" style="width: 30%;margin: 0 auto;" @click="handlerLogin"
                :loading="loading">登录</el-button>
              <el-link type="primary" @click="goRegister">点击注册</el-link>
            </el-form-item>
          </div>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped lang='scss'>
@use "sass:math";

@keyframes meteor {
  0% {
    transform: translateY(0) scale(1);
    opacity: 1;
  }

  70% {
    opacity: 0.8;
  }

  100% {
    transform: translateY(100vh) scale(0.5);
    opacity: 0;
  }
}

.login_container {
  width: 100%;
  height: 100vh;
  background: linear-gradient(to bottom, #0f2027, #203a43, #2c5364);
  position: relative;
  overflow: hidden;

  /* 垂直下落的流星效果 */
  .meteor {
    position: absolute;
    width: 4px;
    height: 4px;
    background: linear-gradient(to bottom, rgba(255, 255, 255, 0.9), rgba(255, 255, 255, 0));
    border-radius: 50%;
    box-shadow: 0 0 15px 3px rgba(255, 255, 255, 0.9);
    animation: meteor 3s linear infinite;

    /* 流星尾部 */
    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 0;
      width: 2px;
      height: 120px;
      background: linear-gradient(to top, rgba(255, 255, 255, 0.9), rgba(255, 255, 255, 0));
    }

    @for $i from 1 through 30 {
      &:nth-child(#{$i}) {
        top: -10px;
        left: math.random(100) + vw;
        animation-delay: math.random(20) + s;
        animation-duration: math.random(3) + 1 + s;
        opacity: math.div(math.random(100), 100) + 0.3;
      }
    }
  }

}

.login_form {
  position: relative;
  width: 80%;
  top: 30vh;
  background-color: rgba(20, 68, 105, 0.4);
  backdrop-filter: blur(5px); // 添加毛玻璃效果
  border-radius: 10px;
  padding: 40px;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.2);
  z-index: 1;

  h1 {
    color: #fff;
    font-size: 40px;
    text-shadow: 0 0 10px rgba(255, 255, 255, 0.3);
  }

  h2 {
    color: #fff;
    font-size: 20px;
    margin: 20px 0;
    text-shadow: 0 0 5px rgba(255, 255, 255, 0.3);
  }

  .form {
    width: 80%;
    margin: auto;

    :deep(.el-input-group__append) {
      padding: 0;
      border: none;
      background: transparent;
      box-shadow: none;
    }
  }
}
</style>